package com.egdigital.allzic.ui.activity;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
import com.android.volley.VolleyError;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserStation;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Station;
import com.egdigital.allzic.ui.ScrollingTextView;
import com.egdigital.allzic.ui.adapter.AdapterListRadio;
import com.egdigital.allzic.utils.NetworkManager;
import com.egdigital.allzic.utils.Utils;

public class ActivitySearch extends BaseActivity implements OnClickListener, OnItemClickListener {

	private static final String	TAG						= ActivitySearch.class.getSimpleName();												// log
	private String				URL_SEARCH				= "http://www.allzicradio.com/json/search : moteur de recherche avec POST['search']";
	private static String		mCurrentSearch			= "";
	private boolean				mAutoCompletionEngoing	= false;
	private List<Station>		mList;
	private JsonParserStation	mJsonParserStation;
	//
	private AdapterListRadio	mAdapter;
	private ListView			mListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_search);
		// actionbar
		ActionBar mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true);
		mActionBar.setTitle(getString(R.string.activity_search_title));
		// views
		mPlayerLayout = (LinearLayout) findViewById(R.id.player_layout);
		mPlayerButtonPlay = (ImageButton) findViewById(R.id.player_play);
		mPlayerButtonFavorite = (ImageButton) findViewById(R.id.player_like);
		mPlayerSubTitle = (ScrollingTextView) findViewById(R.id.player_sub);
		mPlayerTitle = (TextView) findViewById(R.id.player_title);
		mPlayerThumb = (ImageView) findViewById(R.id.player_thumb);
		mPlayerLoading = (ProgressBar) findViewById(R.id.player_loading);
		mPlayerButtonPlay.setEnabled(false);
		mListView = (ListView) findViewById(R.id.activity_search_list);
		mLoadingView = (RelativeLayout) findViewById(R.id.activity_search_loading);
		mReloadView = (LinearLayout) findViewById(R.id.activity_search_reload);
		mNoResultView = (TextView) findViewById(R.id.activity_search_noresult);
		// listener
		mPlayerLayout.setOnClickListener(this);
		mPlayerButtonPlay.setOnClickListener(this);
		mPlayerButtonFavorite.setOnClickListener(this);
		mReloadView.setOnClickListener(this);
		mCurrentSearch = getIntent().getExtras().getString("search");
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
		mJsonParserStation = new JsonParserStation();
		VolleyManager.init(this);
		mJsonParserStation.initAndStartRequestQueue();
		setupSearchCallBack();
	}

	@Override
	protected void onDestroy() {
		mJsonParserStation.stopRequestQueue();
		Utils.cancelToast();
		if (mPlayBackReceiver != null) {
			LocalBroadcastManager.getInstance(this).unregisterReceiver(mPlayBackReceiver);
		}
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.slide_from_behind, R.anim.slide_out_right);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		getSupportMenuInflater().inflate(R.menu.menu_search_only, menu);
		// menu item
		MenuItem searchItem = menu.findItem(R.id.action_search_only);
		SearchView searchView = (SearchView) searchItem.getActionView();
		searchView.setIconifiedByDefault(false);
		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {
				// process search
				mCurrentSearch = query;
				if (query.length() > ActivityHome.CHAR_MIN_BEFORE_SEARCH) {
					if (mAutoCompletionEngoing == false) {
						closeKb();
						loadData(query);
					}
				}
				return true;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				// process search
				mCurrentSearch = newText;
				return true;
			}
		});
		searchView.setQuery(mCurrentSearch, true);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				finish();
				overridePendingTransition(R.anim.slide_from_behind, R.anim.slide_out_right);
				break;
			case R.id.action_close:
				finish();
				overridePendingTransition(R.anim.slide_from_behind, R.anim.slide_out_right);
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case android.R.id.home:
				finish();
				overridePendingTransition(R.anim.slide_from_behind, R.anim.slide_out_right);
				break;
			case R.id.activity_search_reload:
				loadData(mCurrentSearch);
				break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		Station station = mList.get(position);
		prepareToPlay(station);
		showPlayerBanner();
		updatePlayerBanner();
	}

	/**
	 * volley callbacks
	 */
	private void setupSearchCallBack() {
		mJsonParserStation.setJsonCallBack(new JsonCallBack() {

			@Override
			public void downloadStarted() {
				mAutoCompletionEngoing = true;
			}

			@Override
			public void downloadPercent(int percent) {
			}

			@Override
			public <T> void downloadCompleted(List<T> list) {
				mAutoCompletionEngoing = false;
				if (list == null) {
					return;
				}
				if (!list.isEmpty()) {
					mList = (List<Station>) list;
					updateAdapter(mList);
					mNoResultView.setVisibility(View.GONE);
					setLoaded(mListView);
				} else {
					mListView.setAdapter(null);
					setNoResult(mListView);
				}
			}

			@Override
			public void downloadEndedWithError(VolleyError error) {
				mAutoCompletionEngoing = false;
				mListView.setVisibility(View.GONE);
				setReload();
			}
		});
	}

	public void moveToPlayer(boolean doAnimation, Station station) {
		if (station == null) {
			return;
		}
		ActivityMain.setmCurrentStation(station);
		Intent intent = new Intent(this, ActivityPlayer.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra(ActivityPlayer.STATION, (Parcelable) station); // parse the object station
		startActivity(intent);
		finish();
		if (doAnimation) {
			overridePendingTransition(R.anim.slide_in_bottom, R.anim.fade_out);
		}
	}

	private void loadData(String search) {
		if (NetworkManager.isConnected(getApplicationContext())) {
			setLoading(mListView);
			mJsonParserStation.extractJsonObjectData(getString(R.string.url_autocompletion) + search);
		} else {
			mListView.setVisibility(View.GONE);
		}
	}

	private void updateAdapter(List<Station> list) {
		mAdapter = null;
		mAdapter = new AdapterListRadio(getApplicationContext(), list, R.layout.cell_list_radio);
		mListView.setVisibility(View.VISIBLE);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
	}

	private void closeKb() {
		// Close keyboard
		InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
		// check if no view has focus:
		View v = this.getCurrentFocus();
		if (v == null)
			return;
		inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}
}
